package bainuo

import groovy.sql.Sql

def execute() {
    Sql connSource = null
    try {
        // 创建源数据库连接
        connSource = Sql.newInstance(mypara.hqcon(2))

        // 批次大小
        int batchSize = 1000
        List<Map<String, String>> results = []

        // 新的查询语句
        def sql = """select pk_bankdoc, code, name, pcombinenum from bd_bankdoc"""

        // 使用流式查询来处理大数据集
        connSource.eachRow(sql) { row ->
            Map<String, String> item = [
                    "pk_bankdoc": row.pk_bankdoc,
                    "code": row.code,
                    "name": row.name,
                    "pcombinenum": row.pcombinenum
            ]

            results.add(item)

            // 当达到批次大小时，推送数据并清空列表
            if (results.size() >= batchSize) {
                push(["items": results])
                results.clear()
            }
        }

        // 处理剩余的数据
        if (!results.isEmpty()) {
            push(["items": results])
        }
    } catch (Exception e) {
        e.printStackTrace()
        println "Error in execute: ${e.message}"
    } finally {
        if (connSource != null) {
            connSource.close()
        }
    }
}

def push(data) {
    println "-------------------------银行任务启动-------------------------"
    try {
        def items = data.get("items")

        for (def item : items) {
            insertLog(item)
        }
        println "-------------------------传输完成-------------------------"
    } catch (Exception e) {
        e.printStackTrace()
        println "Error in push: ${e.message}"
        return ["state": 0, "Ascript": "请求参数错误,请检查"]
    }
}

static def insertLog(Map<String, String> params) {
    Sql connTarget = null
    try {
        // 连接目标数据库...
        connTarget = Sql.newInstance("jdbc:mysql://10.1.1.209:3306/sqlserver", "oper_dc", "operzADF2020qwer", "com.mysql.cj.jdbc.Driver")

        // 准备插入
        def insertKeys = params.keySet().toList()
        def placeholders = insertKeys.collect { '?' }

        // 构建插入语句
        def sqlStatement = "INSERT INTO bd_bankdoc(" + insertKeys.join(", ") + ") VALUES (" + placeholders.join(", ") + ")"

        // 执行插入操作
        connTarget.execute(sqlStatement, insertKeys.collect { params[it] })

        //println "Record inserted successfully with pk_bankdoc :[${params['pk_bankdoc']}]"
    } catch (Exception e) {
        e.printStackTrace()
        println "Error inserting record: ${e.message}"
    } finally {
        if (connTarget != null) {
            connTarget.close()
        }
    }
}